package com.scoy.honeymei.activity.mall;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.lzy.okgo.model.HttpParams;
import com.scoy.honeymei.R;
import com.scoy.honeymei.adapter.OrderDeAdapter;
import com.scoy.honeymei.base.BaseActivity;
import com.scoy.honeymei.bean.CartBean;
import com.scoy.honeymei.bean.GoodsOrderBean;
import com.scoy.honeymei.bean.MallOrderDetailBean;
import com.scoy.honeymei.dialog.EvaDialog;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.url.ApiCallBack;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.IntentUtil;
import com.scoy.honeymei.utils.MyUtil;
import com.scoy.honeymei.utils.SystemUtil;
import com.scoy.honeymei.wxapi.PayEvent;
import com.scoy.honeymei.wxapi.PayUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: PaySureActivity$
 * @Description: 订单详情界面
 * @Author: GaoZhan
 * @CreateDate: 2019/9/10/0010$ 上午 9:22$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/9/10/0010$ 上午 9:22$
 * @UpdateRemark: 更新内容
 */
public class OrderDetailActivity extends BaseActivity {


    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.title_llt)
    LinearLayout titleLlt;
    @BindView(R.id.ps_iv0)
    ImageView psIv0;
    @BindView(R.id.ps_name_tv)
    TextView psNameTv;
    @BindView(R.id.ps_phone_tv)
    TextView psPhoneTv;
    @BindView(R.id.ps_addressdetail_tv)
    TextView psAddressdetailTv;
    @BindView(R.id.ps_rv)
    RecyclerView psRv;
    @BindView(R.id.ps_tv0)
    TextView psTv0;
    @BindView(R.id.ps_price_tv)
    TextView psPriceTv;
    @BindView(R.id.ps_tv12)
    TextView psTv12;
    @BindView(R.id.ps_allprice_tv)
    TextView psAllpriceTv;
    @BindView(R.id.ps_tv1)
    TextView psTv1;
    @BindView(R.id.ps_leavemes_et)
    EditText psLeavemesEt;
    @BindView(R.id.dtm_tv8)
    TextView dtmTv8;
    @BindView(R.id.dtm_tv9)
    TextView dtmTv9;
    @BindView(R.id.dtm_ordernum_tv)
    TextView dtmOrdernumTv;
    @BindView(R.id.dtm_tv10)
    TextView dtmTv10;
    @BindView(R.id.dtm_creattime_tv)
    TextView dtmCreattimeTv;
    @BindView(R.id.dtm_tv11)
    TextView dtmTv11;
    @BindView(R.id.dtm_paytime_tv)
    TextView dtmPaytimeTv;
    @BindView(R.id.dtm_tv12)
    TextView dtmTv12;
    @BindView(R.id.dtm_endtime_tv)
    TextView dtmEndtimeTv;
    @BindView(R.id.mlo_btn1_tv)
    TextView mloBtn1Tv;
    @BindView(R.id.mlo_btn2_tv)
    TextView mloBtn2Tv;
    @BindView(R.id.mol_btn_cl)
    ConstraintLayout molBtnCl;
    @BindView(R.id.ps_freight_tv)
    TextView psFreightTv;

    @BindView(R.id.dtm_tv13)
    TextView dtmTv13;
    @BindView(R.id.dtm_sendname_tv)
    TextView dtmSendnameTv;
    @BindView(R.id.dtm_tv14)
    TextView dtmTv14;
    @BindView(R.id.dtm_sendphone_tv)
    TextView dtmSendphoneTv;
    @BindView(R.id.ps_tv00)
    TextView psTv00;
    @BindView(R.id.ps_tv0cou)
    TextView psTv0cou;
    @BindView(R.id.ps_cou_tv)
    TextView psCouTv;

    private OrderDetailActivity mContext;
    private ArrayList<CartBean> datalist;
    private int type;
    private int oId;
    private OrderDeAdapter orderAdapter;
    private String orderNo;
    private String payType = "null";
    private String payThree;
    private List<CartBean> goodsList;
    private MallOrderDetailBean.OrderBean order;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        mContext = OrderDetailActivity.this;
        type = getIntent().getIntExtra("type", 0);
        oId = getIntent().getIntExtra("oId", 0);
        if (type == 0) {
            dtmTv11.setVisibility(View.GONE);
            dtmTv12.setVisibility(View.GONE);
        } else if (type == 1) {
            dtmTv12.setVisibility(View.GONE);
            mloBtn1Tv.setVisibility(View.GONE);
            mloBtn2Tv.setText(R.string.surerecive);
        } else if (type == 2) {
            molBtnCl.setVisibility(View.GONE);
        }

        initNormal();

        httpmalldetail();
    }

    @Override
    public void initNormal() {
        datalist = new ArrayList<>();

        titleTv.setText(R.string.orderdetail);
        psLeavemesEt.setEnabled(false);

        MyUtil.setStatusBar(mContext, getWindow(), true, R.color.colorWhite);
        titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);

        initRV();

        EventBus.getDefault().register(this);

    }

    private void initRV() {
        orderAdapter = new OrderDeAdapter(mContext, datalist);
        psRv.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
        DividerItemDecoration did = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        did.setDrawable(getResources().getDrawable(R.drawable.divider_gray_line));
        psRv.addItemDecoration(did);
        psRv.setAdapter(orderAdapter);

    }

    @OnClick({R.id.back_iv, R.id.mlo_btn1_tv, R.id.mlo_btn2_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.mlo_btn1_tv:
                new AlertDialog.Builder(mContext).setTitle("确认取消该订单？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确认", (dialog, which) -> {
                            httpCancle(oId);
                        }).show();

                break;
            case R.id.mlo_btn2_tv:
                if (type == 1) {
                    new AlertDialog.Builder(mContext).setTitle("确认已收货？")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确认", (dialog, which) -> {
                                httpSure(oId);
                            }).show();
                } else if (type == 2) {//评价
                    if (goodsList == null || goodsList.size() == 0) return;

                    CartBean cartBean = goodsList.get(0);
                    List<GoodsOrderBean> goodsAll = cartBean.getGoodsList();

                    ArrayList<GoodsOrderBean> mDataTt = new ArrayList<>();
                    for (GoodsOrderBean aBean : goodsAll) {
                        mDataTt.add(new GoodsOrderBean(aBean.getId(), aBean.getImage(), aBean.getName(), aBean.getMoney(), 0));
                    }
                    GoodsOrderBean osBean = goodsAll.get(0);

                    EvaDialog.newInstance(order.getId(), osBean.getShop_id(), cartBean.getShopname(), mDataTt)
                            .setOnDialogListener(() -> {
                                setResult(0x47);
                                finish();
                            })
                            .show(getSupportFragmentManager(), "");

                } else {  //立即支付
                    showdialog();
                }

                break;
        }
    }

    private void httpmalldetail() {
        HttpParams params = new HttpParams();
        params.put("orderid", oId);
        HpGo.newInstance().HttpGo(this, MyUrl.MALL_ORDER_DETAIL, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                MallOrderDetailBean mallBean = new Gson().fromJson(o, MallOrderDetailBean.class);

                order = mallBean.getOrder();
                orderNo = order.getOrder_sn();
                payThree = order.getPaytype();

                goodsList = mallBean.getGoodsList();
                datalist.addAll(goodsList);
                orderAdapter.notifyDataSetChanged();

                psNameTv.setText(order.getConsignee());
                psPhoneTv.setText(order.getMobile());
                psAddressdetailTv.setText(order.getAddress());
                psLeavemesEt.setText(order.getContent());
                psPriceTv.setText("¥" + order.getPrice());
                psAllpriceTv.setText("¥" + order.getPay_price());
                psFreightTv.setText("¥" + order.getFreight());
                if(order.getCoupon_fee()!=null){
                    psCouTv.setText("¥" + order.getCoupon_fee());
                }else {
                    psCouTv.setText("¥ 0.00");
                }

                dtmOrdernumTv.setText(order.getOrder_sn());
                dtmCreattimeTv.setText(order.getCreate_time());
//                dtmPaytimeTv.setText(order.getPay_time());
                String status = order.getStatus();
                //1为代付款 2为代发货 3为待收货 4为已完成 5已评价",
                if ("5".equals(status)) {
                    psLeavemesEt.setEnabled(false);
                    dtmPaytimeTv.setText(order.getPay_time());
                    dtmTv13.setVisibility(View.VISIBLE);
                    dtmTv14.setVisibility(View.VISIBLE);
                    dtmSendnameTv.setText(order.getExpress_company());
                    dtmSendphoneTv.setText(order.getExpress_no());
                } else if ("4".equals(status)) {
                    molBtnCl.setVisibility(View.VISIBLE);
                    mloBtn1Tv.setVisibility(View.GONE);
                    mloBtn2Tv.setText("立即评价");
                    dtmPaytimeTv.setText(order.getPay_time());
                    dtmTv13.setVisibility(View.VISIBLE);
                    dtmTv14.setVisibility(View.VISIBLE);
                    dtmSendnameTv.setText(order.getExpress_company());
                    dtmSendphoneTv.setText(order.getExpress_no());
                } else if ("3".equals(status)) {
                    dtmTv13.setVisibility(View.VISIBLE);
                    dtmTv14.setVisibility(View.VISIBLE);
                    dtmSendnameTv.setText(order.getExpress_company());
                    dtmSendphoneTv.setText(order.getExpress_no());

                    dtmPaytimeTv.setText(order.getPay_time());
                } else if ("2".equals(status)) {
                    dtmTv13.setVisibility(View.INVISIBLE);
                    dtmTv14.setVisibility(View.INVISIBLE);
//                    dtmSendnameTv.setVisibility(View.INVISIBLE);
//                    dtmSendphoneTv.setVisibility(View.INVISIBLE);
                    dtmPaytimeTv.setText(order.getPay_time());
                }

            }
        });

    }

    private void httpCancle(int orderid) {
        HttpParams params = new HttpParams();
        params.put("orderid", orderid);
        HpGo.newInstance().HttpGo(this, MyUrl.MALL_ORDER_DELETE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                MyUtil.mytoast(mContext, "删除成功");
                setResult(0x47);
                finish();
            }
        });

    }

    private void httpSure(int orderid) {
        HttpParams params = new HttpParams();
        params.put("orderid", orderid);
        HpGo.newInstance().HttpGo(this, MyUrl.MALL_ORDER_SURE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                setResult(0x47);
                finish();
            }
        });
    }

    /**
     * 选择弹窗
     */
    private void showdialog() {
        final Dialog dialogpay = new Dialog(this, R.style.BottomDialogStyle);
        View view = View.inflate(this, R.layout.dialog_tocheckpay_wallet, null);

        ImageView imgClose = view.findViewById(R.id.imgClose);
        Button btnSure = view.findViewById(R.id.btnSure);
        TextView alipayTv = view.findViewById(R.id.txtZhifubao);
        TextView wxpayTv = view.findViewById(R.id.txtWechat);
        TextView walletTv = view.findViewById(R.id.txtWallet);

        dialogpay.setOnDismissListener(dialog -> {
            payType = "null";
        });

        imgClose.setOnClickListener(view1 -> dialogpay.dismiss());
        alipayTv.setOnClickListener(v -> {
            alipayTv.setSelected(true);
            wxpayTv.setSelected(false);
            walletTv.setSelected(false);
            payType = "alipay";
        });
        walletTv.setOnClickListener(v -> {
            walletTv.setSelected(true);
            wxpayTv.setSelected(false);
            alipayTv.setSelected(false);
            payType = "balance";
        });
        wxpayTv.setOnClickListener(v -> {
            alipayTv.setSelected(false);
            wxpayTv.setSelected(true);
            walletTv.setSelected(false);
            payType = "wechat";
        });
        btnSure.setOnClickListener(view12 -> {
            if (!"null".equals(payType)) {
                if ("wechat".equals(payType) || "alipay".equals(payType)) {
                    payOrder(payType);
                } else if ("balance".equals(payType)) {
                    payBalance(payType);
                }
                dialogpay.dismiss();
            }
        });

        dialogpay.setContentView(view);
        dialogpay.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialogpay.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (SystemUtil.getScreenWidth(mContext));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        dialogpay.show();

    }

    //订单未支付支付
    private void payOrder(String payType) {
        HttpParams params = new HttpParams();
        params.put("orderid", oId);
        params.put("type", payType);

        HpGo.newInstance().HttpGo(mContext, MyUrl.ORDER_PAY_ORDER, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                // payThree  1  三方； 2  原生
                if ("2".equals(payThree)) {
                    if ("false".equals(o)) {
                        MyUtil.mytoast(mContext, "支付错误");
                        return;
                    }
                    PayUtil.toPayPayPay(mContext, payType, o);//支付
                } else {
                    if ("alipay".equals(payType)) {
                        IntentUtil.openAPP(mContext, MyUrl.APP_OPEN_ALIPAY + o);
                        finish();
                    } else {
                        if ("false".equals(o)) {
                            MyUtil.mytoast(mContext, "支付错误");
                            return;
                        }
                        PayUtil.toPayPayPay(mContext, payType, o);//支付
                        //  IntentUtil.openAPP(mContext, MyUrl.APP_OPEN_WX + o);
                    }

                }
            }
        });

    }

    private void payBalance(String payType) {
        HttpParams params = new HttpParams();
        params.put("orderid", oId);

        HpGo.newInstance().HttpGo(mContext, MyUrl.ORDER_PAY_BALANCE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                MyUtil.mytoast0(mContext, "支付成功", R.mipmap.ic_sure);
                setResult(0x47);
                finish();
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent event) {
        int type = event.getType();//0 成功 -1失败 -2取消
        if (type == 0) {
            MyUtil.mytoast0(mContext, "支付成功", R.mipmap.ic_sure);
            setResult(0x47);
            finish();
        } else if (type == -1) {
            MyUtil.mytoast(mContext, "支付失败");
        } else {
            MyUtil.mytoast(mContext, "支付取消");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
